<?php

namespace app\admin\controller\litestore;

use app\common\controller\Backend;
use app\common\controller\Fedex;
use app\common\controller\Usps;
use app\common\library\Ems as Emslib;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Litestoreorder extends Backend
{
    
    /**
     * Litestoreorder模型对象
     * @var \app\admin\model\Litestoreorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\litestore\Litestoreorder;
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("freightStatusList", $this->model->getFreightStatusList());
        $this->view->assign("receiptStatusList", $this->model->getReceiptStatusList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['address'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['address'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','user_id','order_no','total_price','pay_price','pay_time','express_price','freight_time','receipt_time','order_status','updatetime']);
                $row->visible(['address']);
//				$row->getRelation('address')->visible(['first_name','last_name']);
                $row->address->name = $row->address->first_name.' '.$row->address->last_name;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function detail(){
        if($this->request->isPost())
        {
            $id = input('post.ids');
            $row = $this->model->get($id,['goods','address']);
            $row['freight_status'] = "20";
            $row['freight_time'] = time();
            $row['express_company'] = input('post.virtual_name');
            $row['express_no'] = input('post.virtual_sn');
            $row->save();

//            $create_ship = (new Fedex())->create_ship($row['goods'],$row['address']);
//            $create_ship = (new Fedex())->create_ship_test();
//            halt($create_ship);
            //邮件通知
            $email = $row['address']['email_address'];
            $ret = Emslib::order_notice($email, $row,'fahuo');

            $this->success();
        }

        $param = $this->request->param();
        $row = $this->model->get($param['ids']);
        $row->address->service_name = $country_code = Db::name('fedex')->where('code',$row->address->service)->value('title');
        foreach ($row->goods as $k=>$v){
            $v['activity_label'] = '';
            if($v['activity_full_id']){
                $v['activity_label'] = Db::name('activity_full')->where('id',$v['activity_full_id'])->value('label');
            }
        }
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                Db::name('litestore_order_address_en')->where('order_id',$item->id)->delete();
                Db::name('litestore_order_goods')->where('order_id',$item->id)->delete();
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    //确认收货
    public function finish($ids){
        if ($this->model->finish($ids)) {
            return $this->success('');
        }
        return $this->error($this->model->getError());
    }

    //取消订单
    public function cancel($ids){
        $order = $this->model->getOrderDetail($ids);

        if ($order->cancel($ids)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    /**
     * 物流信息
     */
    public function express_info(){
        $param = $this->request->param();
        $row = $this->model->get($param['ids'],['address']);
        if($row['address']['express_company'] == 'Fedex'){
            $express_info = (new Fedex())->get_fedex_info($row['express_no']);
        }else{
            $express_info = (new Usps())->get_usps_info($row['express_no']);
        }
//        halt($express_info);

        $error_info = '';
        if($express_info['code'] == 10){
            $express_info = [];
            $error_info = 'Tracking number cannot be found. Please correct the tracking number and try again.';
        }else{
            $express_info = $express_info['data'];
        }

        $this->view->assign('error_info', $error_info);
        $this->view->assign('vo', $express_info);
        return $this->view->fetch();
    }
}
